import { createRouter, createWebHistory } from "vue-router";
import type { RouteRecordRaw } from "vue-router";
import { useUserStore } from "../store/user";

const whiteList = ["/login", "/register", "/forgot"];

const routes: Array<RouteRecordRaw> = [
  {
    path: "/",
    redirect: "/home",
  },
  {
    path: "/login",
    name: "Login",
    component: () => import("../views/Login/index.vue"),
  },
  {
    path: "/register",
    name: "Register",
    component: () => import("../views/Login/Registe.vue"),
  },
  {
    path: "/forgot",
    name: "ForgotPassword",
    component: () => import("../views/Login/ForgotPassword.vue"),
  },
  {
    path: "/",
    component: () => import("../components/Layout.vue"),
    children: [
      {
        path: "home",
        name: "Home",
        component: () => import("../views/Home/index.vue"),
      },
      // 其他页面...
    ],
  },
];

const router = createRouter({
  // @ts-ignore
  history: createWebHistory(import.meta.env.BASE_URL),
  routes,
});

router.beforeEach((to, _, next) => {
  const userStore = useUserStore();

  if (userStore.token) {
    // 已登录
    if (to.path === "/login") {
      next("/home");
    } else {
      next();
    }
  } else {
    // 未登录
    if (whiteList.includes(to.path)) {
      next();
    } else {
      next("/login");
    }
  }
});

export default router;
